﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MachiningHelper.ToolFile;
using System.Data;
using System.Data.OleDb;
using Dapper;

namespace Skipper_Connector
{
    public class BusinessHelper
    {
        public static bool CheckRepeatBarcode(string barcode)
        {
            bool result = true;
            if (!Config.OpenCheckRepeat)
                return result;

            string file = Path.Combine(Application.StartupPath, "MachiningBarcode.log");
            if (!File.Exists(file))
                File.Create(file).Close();

            using (StreamReader sr = new StreamReader(file))
            {
                while (!sr.EndOfStream)
                {
                    if (barcode == sr.ReadLine())
                    {
                        DialogResult warning = MessageBox.Show(barcode + "该条码已经扫描过，是否仍要进行加工？", "重码提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                        if (warning == DialogResult.Cancel)
                        {
                            result = false;
                        }
                        break;
                    }
                }
            }
            if (result)
            {
                using (StreamWriter sw = new StreamWriter(file, true))
                {
                    sw.WriteLine(barcode);
                    sw.Close();
                }
            }
            return result;
        }

        public static void Clear()
        {
            string file = Path.Combine(Application.StartupPath, "MachiningBarcode.log");
            if (!File.Exists(file))
                return;
            string[] lines = File.ReadAllLines(file);
            int count = lines.Count();
            if (count > 3000)
            {
                File.WriteAllText(file, string.Join(Environment.NewLine, lines, count - 1500, 1500));
            }
        }

        private static string mdbStr(string mdbfile)
        {
            if (!File.Exists(mdbfile))
                return mdbfile + ".finish";
            else
                return mdbfile;
        }

        public static bool RecordPart(MachiningPart part, string barcode)
        {
            if (!Config.OpenCheckRepeat)
                return true;
            string mdb = Path.Combine(Config.DataPath, part.Border.JobName + ".mdb");
            mdb = mdbStr(mdb);

            if (!File.Exists(mdb))
                return CheckRepeatBarcode(barcode);
            if (string.IsNullOrEmpty(part.Border.FileName))
                return true;
            string serchStr = Config.IsChangeBarcode ? part.Border.FileName : barcode;
            string connString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + mdb;
            using (var conn = new OleDbConnection(connString))
            {
                conn.Open();
                var checkFilename = conn.Query<string>(string.Format("Select {0} from CombinedParts Where {0}='{1}'", "[File Name]", part.Border.FileName), null);
                if (checkFilename.Count() < 1)
                    throw new Exception("该订单的板件数据库与加工数据不匹配");
                OleDbCommand cmd = new OleDbCommand(string.Format("Update CombinedParts Set [Qty]=Qty-1 where PartsCounter in (SELECT Top 1 PartsCounter From CombinedParts Where [File Name]='{0}' AND Qty>0)", serchStr), conn);

                if (cmd.ExecuteNonQuery() == 0)
                {
                    DialogResult warning = MessageBox.Show(barcode + "该条码已经扫描过，是否仍要进行加工？", "重码提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (warning == DialogResult.Cancel)
                        return false;
                    return true;
                }
                else
                {
                    var qty = conn.Query<int>("Select Qty from CombinedParts Where Qty>0", null).ToList();
                    if (qty.Count == 0)
                    {
                        conn.Dispose();
                        FileInfo fi = new FileInfo(mdb);
                        fi.MoveTo(mdb + ".finish");
                    }
                    return true;
                }
            }
        }

        public static List<CombinedPart> Report(string mdbName)
        {
            string mdb = Path.Combine(Config.DataPath, mdbName);
            string connString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + mdb;
            using (var conn = new OleDbConnection(connString))
            {
                conn.Open();
                var parts = conn.Query<CombinedPart>("Select * from CombinedParts Where Qty>0 AND [File Name]<>null", null).ToList<CombinedPart>();
                string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "未加工板件清单");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                StreamWriter sw = new StreamWriter(Path.Combine(path, mdbName.Replace("mdb", "csv")), false, Encoding.GetEncoding("GB2312"));
                sw.WriteLine("产品序号,板件序号,板件名称,未完成数量,长度,宽度,厚度,材料,条码");
                foreach (var part in parts)
                {
                    sw.WriteLine(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
                        part.ProductsIndex,
                        part.PartsIndex,
                        part.PartName,
                        part.Qty,
                        part.Length,
                        part.Width,
                        part.Thickness,
                        part.Material,
                        part.Barcode));
                }
                sw.Close();
                return parts;
            }
        }
    }
}
